from django.http import JsonResponse, QueryDict
from django.views import View
from kubernetes import client, config
from libs import k8s
import os,json

class pvc_api(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()

    def get(self,request):
        data = []
        search_key = request.GET.get("query")
        namespace = request.GET.get("namespace")
        try:
            for item in self.core_api.list_namespaced_persistent_volume_claim(namespace=namespace).items:
                name = item.metadata.name
                namespace = item.metadata.namespace
                labels = item.metadata.labels
                storage_class_name = item.spec.storage_class_name
                access_modes = item.spec.access_modes
                capacity = (item.status.capacity if item.status.capacity is None else item.status.capacity["storage"])
                volume_name = item.spec.volume_name
                status = item.status.phase
                create_time = k8s.timestamp_format(item.metadata.creation_timestamp)

                pvc = {"name": name, "namespace": namespace, "lables": labels,
                       "storage_class_name": storage_class_name, "access_modes": access_modes, "capacity": capacity,
                       "volume_name": volume_name, "status": status, "create_time": create_time}
                # 根据查询关键字返回数据
                if search_key:
                    if search_key in name:
                        data.append(pvc)
                else:
                    data.append(pvc)
            code = 200
            msg = "查询成功."
        except Exception as e:
            status = getattr(e, 'status')
            if status == 403:
                msg = "没有访问权限！"
            else:
                msg = "查询失败！"
            code = 500

        # 分页
        count = len(data)  # 要在切片之前获取总数

        page = int(request.GET.get('pageNum', 1))  # 当前第几页
        limit = int(request.GET.get('pageSize',10))   # 当前页的数据数量
        # data = data[0:10]
        start = (page - 1) * limit  # 切片的起始值
        end = page * limit  # 切片的末值
        data = data[start:end]  # 返回指定数据范围

        result = {'code': code, 'msg': msg, 'data': data, 'count': count}
        return JsonResponse(result)
    def post(self,request):
        data = json.loads(request.body.decode("utf-8"))
        name = data["name"]
        namespace = data["namespace"]
        capacity = data["capacity"]
        access_mode = data["access_mode"]
        storageclass = data["storageclass"]

        try:
            body = client.V1PersistentVolumeClaim(
                api_version="v1",
                kind="PersistentVolumeClaim",
                metadata=client.V1ObjectMeta(name=name),
                spec=client.V1PersistentVolumeClaimSpec(
                    access_modes=[access_mode],
                    resources=client.V1ResourceRequirements(
                        requests={"storage": capacity}
                    ),
                    storage_class_name=storageclass
                )
            )
            self.core_api.create_namespaced_persistent_volume_claim(namespace=namespace,body=body)
            code = 200
            msg = "创建成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 400:
                msg = "数据格式错误！"
            elif status == 403:
                msg = "没有访问权限！"
            elif status == 409:
                msg = "pvc已存在！"
            else:
                msg = "服务端处理失败！"
            code = 500
        result = {'code': code, 'msg': msg}
        return JsonResponse(result)
    def delete(self,request):
        data = json.loads(request.body.decode("utf-8"))
        name = data['name']
        namespace = data.get('namespace')
        try:
            self.core_api.delete_namespaced_persistent_volume_claim(namespace=namespace, name=name)
            code = 0
            msg = "删除成功."
        except Exception as e:
            status = getattr(e, 'status')
            if status == 403:
                msg = "没有访问权限！"
            else:
                msg = "删除失败！"
            code = 500

        result = {'code': code, 'msg': msg}
        return JsonResponse(result)


class pv_api(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()

    def get(self,request):
        # 查询
        search_key = request.GET.get('query')

        data = []  # [{},{},{}]
        try:
            for item in self.core_api.list_persistent_volume().items:
                name = item.metadata.name
                capacity = item.spec.capacity["storage"]
                access_modes = item.spec.access_modes
                reclaim_policy = item.spec.persistent_volume_reclaim_policy
                status = item.status.phase
                if item.spec.claim_ref is not None:
                    pvc_ns = item.spec.claim_ref.namespace
                    pvc_name = item.spec.claim_ref.name
                    pvc = "%s / %s" % (pvc_ns, pvc_name)
                else:
                    pvc = "未绑定"
                storage_class = item.spec.storage_class_name
                create_time = k8s.timestamp_format(item.metadata.creation_timestamp)
                d = {"name": name, "capacity": capacity, "access_modes":access_modes,
                             "reclaim_policy":reclaim_policy , "status":status, "pvc":pvc,
                            "storage_class":storage_class,"create_time": create_time}
                if search_key:
                    if search_key in name:  # 实现模糊匹配
                        data.append(d)
                else:
                    data.append(d)
            code = 200
            msg = "查询成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:  #  400 格式错误，409 资源存在，403 没权限。
                msg = "没有访问权限！"
            else:
                msg = "查询失败！"
            code = 500

        count = len(data)
        # 分页
        page = int(request.GET.get('pageNum', 1))  # 当前第几页
        limit = int(request.GET.get('pageSize',10))   # 当前页的数据数量
        start = (page - 1) * limit  # 获取切片的起始值
        end = page * limit # 获取切片的结束值
        data = data[start:end]

        result = {'code': code, 'msg': msg, 'count': count, 'data': data}
        return JsonResponse(result)
    def post(self,request):
        # 创建
        data = json.loads(request.body.decode("utf-8"))
        name = data["name"]
        capacity = data["capacity"]
        access_mode = data["access_mode"]
        storage_type = data["storage_type"]
        server_ip = data["storage_ip"]
        share_path = data["storage_share_path"]

        try:
            body = client.V1PersistentVolume(
                api_version="v1",
                kind="PersistentVolume",
                metadata=client.V1ObjectMeta(name=name),
                spec=client.V1PersistentVolumeSpec(
                    capacity={'storage': capacity},
                    access_modes=[access_mode],
                    nfs=client.V1NFSVolumeSource(
                        server=server_ip,
                        path=share_path
                    )
                )
            )
            self.core_api.create_persistent_volume(body=body)
            code = 200
            msg = "创建成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 400:
                msg = "数据格式错误！"
            elif status == 403:
                msg = "没有访问权限！"
            elif status == 409:
                msg = "pv已存在！"
            else:
                msg = "服务端处理失败！%s" %e
            code = 500
        result = {'code': code, 'msg': msg}
        return JsonResponse(result)
    def delete(self,request):
        # 删除
        data = json.loads(request.body.decode("utf-8"))
        name = data['name']
        try:
            self.core_api.delete_persistent_volume(name=name)
            code = 200
            msg = "删除成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "没有访问权限！"
            else:
                msg = "删除失败！"
            code = 500
        result = {'code': code, 'msg': msg}
        return JsonResponse(result)
    def put(self,request):
        # 更新
        pass


class configmap_api(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()

    def get(self,request):
        data = []
        search_key = request.GET.get("query")
        namespace = request.GET.get("namespace")
        try:
            for item in self.core_api.list_namespaced_config_map(namespace=namespace).items:
                name = item.metadata.name
                namespace = item.metadata.namespace
                data_length = ("0" if item.data is None else len(item.data))
                create_time = k8s.timestamp_format(item.metadata.creation_timestamp)

                d = {"name": name, "namespace": namespace, "data_length": data_length, "create_time": create_time}
                # 根据查询关键字返回数据
                if search_key:
                    if search_key in name:
                        data.append(d)
                else:
                    data.append(d)
            code = 200
            msg = "查询成功."
        except Exception as e:
            status = getattr(e, 'status')
            if status == 403:
                msg = "没有访问权限！"
            else:
                msg = "查询失败！"
            code = 500

        # 分页
        count = len(data)  # 要在切片之前获取总数

        page = int(request.GET.get('pageNum', 1))  # 当前第几页
        limit = int(request.GET.get('pageSize',10))   # 当前页的数据数量
        # data = data[0:10]
        start = (page - 1) * limit  # 切片的起始值
        end = page * limit  # 切片的末值
        data = data[start:end]  # 返回指定数据范围

        result = {'code': code, 'msg': msg, 'data': data, 'count': count}
        return JsonResponse(result)

    def delete(self,request):
        data = json.loads(request.body.decode("utf-8"))
        name = data['name']
        namespace = data.get('namespace')
        try:
            self.core_api.delete_namespaced_config_map(name=name,namespace=namespace)
            code = 0
            msg = "删除成功."
        except Exception as e:
            status = getattr(e, 'status')
            if status == 403:
                msg = "没有访问权限！"
            else:
                msg = "删除失败！"
            code = 500

        result = {'code': code, 'msg': msg}
        return JsonResponse(result)


class secret_api(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()

    def get(self,request):
        data = []
        search_key = request.GET.get("query")
        namespace = request.GET.get("namespace")
        print(namespace,111)
        try:
            for item in self.core_api.list_namespaced_secret(namespace=namespace).items:
                name = item.metadata.name
                namespace = item.metadata.namespace
                type = item.type
                data_length = ("空" if item.data is None else len(item.data))
                create_time = k8s.timestamp_format(item.metadata.creation_timestamp)

                d = {"name": name, "namespace": namespace, "type": type, "data_length": data_length, "create_time": create_time}
                # 根据查询关键字返回数据
                if search_key:
                    if search_key in name:
                        data.append(d)
                else:
                    data.append(d)

            code = 200
            msg = "查询成功."
        except Exception as e:
            msg = "查询失败！%s" %e
            code = 500

        # 分页
        count = len(data)  # 要在切片之前获取总数

        page = int(request.GET.get('pageNum', 1))  # 当前第几页
        limit = int(request.GET.get('pageSize',10))   # 当前页的数据数量
        # data = data[0:10]
        start = (page - 1) * limit  # 切片的起始值
        end = page * limit  # 切片的末值
        data = data[start:end]  # 返回指定数据范围

        result = {'code': code, 'msg': msg, 'data': data, 'count': count}
        return JsonResponse(result)

    def delete(self,request):
        data = json.loads(request.body.decode("utf-8"))
        name = data['name']
        namespace = data.get('namespace')
        try:
            self.core_api.delete_namespaced_secret(namespace=namespace, name=name)
            code = 200
            msg = "删除成功."
        except Exception as e:
            status = getattr(e, 'status')
            if status == 403:
                msg = "没有访问权限！"
            else:
                msg = "删除失败！"
            code = 500

        result = {'code': code, 'msg': msg}
        return JsonResponse(result)


class storageclass_api(View):

    k8s.load_auth_config()
    storage_api = client.StorageV1Api()

    def get(self,request):
        # 查询
        search_key = request.GET.get('query')

        data = []  # [{},{},{}]
        try:
            for item in self.storage_api.list_storage_class().items:
                name = item.metadata.name
                provisioner = item.provisioner
                parameters = item.parameters
                reclaim_policy = item.reclaim_policy
                allow_volume_expansion = "是" if item.allow_volume_expansion else "否"
                create_time = k8s.timestamp_format(item.metadata.creation_timestamp)
                d = {"name": name, "provisioner": provisioner, "parameters":parameters,
                    "reclaim_policy":reclaim_policy , "allow_volume_expansion":allow_volume_expansion,
                    "create_time": create_time}
                if search_key:
                    if search_key in name:  # 实现模糊匹配
                        data.append(d)
                else:
                    data.append(d)
            code = 200
            msg = "查询成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:  #  400 格式错误，409 资源存在，403 没权限。
                msg = "没有访问权限！"
            else:
                msg = "查询失败！"
            code = 500

        count = len(data)
        # 分页
        page = int(request.GET.get('pageNum', 1))  # 当前第几页
        limit = int(request.GET.get('pageSize',10))   # 当前页的数据数量
        start = (page - 1) * limit  # 获取切片的起始值
        end = page * limit # 获取切片的结束值
        data = data[start:end]

        result = {'code': code, 'msg': msg, 'count': count, 'data': data}
        return JsonResponse(result)
    def post(self,request):
        pass
    def delete(self,request):
        # 删除
        data = json.loads(request.body.decode("utf-8"))
        name = data['name']
        try:
            self.storage_api.delete_storage_class(name=name)
            code = 200
            msg = "删除成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "没有访问权限！"
            else:
                msg = "删除失败！"
            code = 500
        result = {'code': code, 'msg': msg}
        return JsonResponse(result)
    def put(self,request):
        # 更新
        pass